package net.assassin.model
{
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import flash.utils.Dictionary;
	
	import mx.core.FlexGlobals;
	
	import net.assassin.model.contributors.IItemContributor;
	import net.assassin.model.contributors.IListContributor;
	import net.assassin.views.ItemViewTemplete;
	import net.assassin.views.ListViewTemplete;

	public class Model
	{
		private static var instance:Model;
		public static function getInstance():Model
		{
			if (instance == null)
			{
				instance = new Model();
			}
			
			return instance;
		}
		
		[Bindable] public var listContributor:IListContributor;
		[Bindable] public var currentItem:IItemContributor;
		
		public var sampleListScrollPositions:Dictionary;
		
		public function Model()
		{
			/*listContributor = new ContributorData();
			currentItem = listContributor;
			
			sampleListScrollPositions = new Dictionary(true);*/
			
			FlexGlobals.topLevelApplication.systemManager.stage.addEventListener(KeyboardEvent.KEY_UP, deviceKeyUpHandler);
		}
		
		
		private function deviceKeyUpHandler(event:KeyboardEvent):void
		{
			var key:uint = event.keyCode;
			
			if (key == Keyboard.BACK && FlexGlobals.topLevelApplication.canCancelBackKeyBehavior){//add listener for key.back is not so googd we should listen for pop view.
				if ((FlexGlobals.topLevelApplication.navigator.activeView is ListViewTemplete) || (FlexGlobals.topLevelApplication.navigator.activeView is ItemViewTemplete))
				{
					var newItem:IListContributor =  Model.getInstance().findParent(Model.getInstance().currentItem);
					if (newItem != null)
					{
						Model.getInstance().currentItem = newItem;
					}
				}
			}
		}

		public function init(listContributor:IListContributor):void{
			this.listContributor = listContributor;
			currentItem = this.listContributor;
			
			sampleListScrollPositions = new Dictionary(true);
		}
		
		public function findParent(item:IItemContributor):IListContributor
		{
			return getParentOf(item, listContributor);
		}
		
		protected function getParentOf(item:IItemContributor, searchNode:IListContributor):IListContributor
		{
			for each(var si:IItemContributor in searchNode.itemContributors)
			{
				if (si == item)
				{
					return searchNode;
				}
				else if (si is IListContributor)
				{
					var i:IListContributor = getParentOf(item, si as IListContributor);
					if (i != null)
					{
						return i;
					}
				}
			}
			
			return null;
		}
	}
}